package com.sduept.nwld.fault.handler;

import com.sduept.bigdata.fault.analysis.handler.impl.AbstractCommonHandler;
import com.sduept.bigdata.fault.common.FaultAlarmDesc;
import com.sduept.bigdata.fault.common.FaultHandlerContext;
import com.sduept.bigdata.fault.common.HandlerContext;
import com.sduept.bigdata.fault.entity.RequestUnfinishedTask;
import com.sduept.bigdata.fault.manager.RequestUnfinishedTaskManager;
import com.sduept.bigdata.fault.manager.RequestUnfinishedTaskManager.RequestService;
import com.sduept.generator.ObjectId;
import com.sduept.message.entity.AlarmMessage;
import com.sduept.message.entity.AlarmMessageCheck;
import com.sduept.message.entity.AlarmMessageWrapper;
import com.sduept.message.exception.MessageException;
import com.sduept.message.manager.AlarmMessageManager;
import com.sduept.utils.DateUtil;
import com.sduept.utils.SpringContext;

import java.util.Date;
import java.util.HashSet;
import java.util.List;

public class AlarmAnalysisHandler extends AbstractCommonHandler {
	private RequestUnfinishedTaskManager runManager = SpringContext.getBean(RequestUnfinishedTaskManager.class);
	private AlarmMessageManager mm = SpringContext.getBean(AlarmMessageManager.class);
	/**
	 * 保护装置告警、一次设备告警分析模板
	 */
	private String template1="保护装置异常告警分析【分析日期：#{date}】：\r\n" + 
								"1、检修票分析情况：系统通信#{oServiceStatus}，数据获取#{oServiceStatus}，直调检修系统#{oExist}检修记录。\r\n" + 
								"2、EMS系统分析情况：系统通信#{eServiceStatus}，数据获取#{eServiceStatus}，该时间段内开关和刀闸#{bStatus}。\r\n" + 
								"分析结论：#{conclusion}";
	
	@Override
	public void logic(HandlerContext context) {
		FaultHandlerContext faultContext = (FaultHandlerContext)context;
		List<FaultAlarmDesc> list= faultContext.getAlarms();
		if(list.size()==0 || faultContext.getCurrentFaultRecord().getStatus()==1) {
			return;
		}
		template1 = template1.replace("#{date}", DateUtil.getStringDate(new Date(),DateUtil.pattern_ymdhms));
		int serviceCheck = serviceCheck(faultContext.getCurrentFaultRecord().getFaultTime());
		String conclusion="本次告警无法判别告警原因，需要人员进一步核查。;";
		boolean flag1 = false;
		boolean flag2 = false;
		//设置EMS服务状态
		if((serviceCheck & 1)>0) {
			template1 = template1.replace("#{eServiceStatus}", "异常");
			template1 = template1.replace("#{bStatus}", "状态未知");
			flag1 = true;
		}else if((faultContext.getEfileCheckResult()==-1)){
			template1 = template1.replace("#{eServiceStatus}", "正常");
			template1 = template1.replace("#{bStatus}", "状态未知（原因：系统解析服务超时）");
		}else if((faultContext.getEfileCheckResult()==-2)){
			template1 = template1.replace("#{eServiceStatus}", "正常");
			template1 = template1.replace("#{bStatus}", "状态未知（原因：模型未配置本次检测的设备）");
		}else if(faultContext.getEfileCheckResult()==0) {
			template1 = template1.replace("#{eServiceStatus}", "正常");
			template1 = template1.replace("#{bStatus}", "在合位");
		}
		// 设置检修服务状态
		if((serviceCheck & 2)>0) {
			template1 = template1.replace("#{oServiceStatus}", "异常");
			template1 = template1.replace("#{oExist}", "无");
			flag2 = true;
		}else {
			template1 = template1.replace("#{oServiceStatus}", "正常");
			template1 = template1.replace("#{oExist}", "无");
		}
		if(flag1 && flag2) {
			template1 = template1.replace("#{conclusion}",conclusion);
		}else {
			template1 = template1.replace("#{conclusion}","本次告警初步判断装置或回路有异常，建议由一次专业进一步检查");
		}
		for(FaultAlarmDesc d:list) {
			AlarmMessage am = new AlarmMessage();
			am.setId(ObjectId.get().toString());
			List<AlarmMessage> dblist = dao.findByCondition(AlarmMessage.class, "createTime=? AND content=?", faultContext.getCurrentFaultRecord().getFaultTime(),d.getContent());
			if(dblist.size()>0) {
				am.setId(dblist.get(0).getId());
			}
			am.setSource(d.getSourceId());
			am.setCreateTime(faultContext.getCurrentFaultRecord().getFaultTime());
			am.setStationId(d.getStationId());
			am.setStationName(d.getStationName());
			am.setPrimaryId(d.getPrimaryId());
			am.setPrimaryName(d.getPrimaryName());
			am.setContent(d.getContent());
			am.setMsgType(d.getAlarmConfig().getId());	
			am.setTimeliness(Long.parseLong(d.getAlarmConfig().getValue()));		
			AlarmMessageWrapper alarmMessageWrapper = new AlarmMessageWrapper();
			alarmMessageWrapper.setAlarmMessage(am);
			alarmMessageWrapper.setCodes(new HashSet<String>());
			alarmMessageWrapper.setForce(false);
			alarmMessageWrapper.setGenerateCheckResult(true);
			AlarmMessageCheck alarmMessageCheck = alarmMessageWrapper.getAlarmMessageCheckByAlarmMessage();
			alarmMessageCheck.setAnalyseResult(template1);
			try {
				mm.generateMsg(alarmMessageWrapper);
			} catch (MessageException e) {
				e.printStackTrace();
			}
		}
	}
	
	private int serviceCheck(Date date) {
		int status = 0;
		List<RequestUnfinishedTask> list2 = runManager.getRequestUnfinishedTask(RequestService.efileService, date);
		if(list2.size()>0) {
			status = status|1;
		}
		List<RequestUnfinishedTask> list3 = runManager.getRequestUnfinishedTask(RequestService.overhaualService, date);
		if(list3.size()>0) {
			status = status|2;
		}
		return status;
	}
	
}
